const { app, BrowserWindow } = require('electron');
const path = require('path');

const isPro = process.env.NODE_ENV !== 'development';

function createWindow() {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: true,
    },
  });

  if (isPro) {
    // 通过file协议加载
    const filePath = path.join(__dirname, '..', 'render', 'index.html');
    mainWindow.loadFile(filePath);
  } else {
    const load = () => {
      mainWindow
        .loadURL('http://localhost:8080')
        .catch(() => setTimeout(load, 3000));
    };
    load();
  }
  mainWindow.webContents.openDevTools();
  return mainWindow;
}

app.whenReady().then(() => {
  let mainWindow = createWindow();
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) mainWindow = createWindow();
  });

  require('./src/initMenu')(mainWindow);
  require('./src/handleMsg')(mainWindow);
});
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});
